"""
Case Type   : datakit安装
Case Name   : 插件卸载
Create At   : 2025/4/21
Owner       : @lonely-dance
Description :
    1.卸载插件
    2.恢复环境
Expect      :
    1.成功
    2.成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.datakit_api.CommonApi import CommonApi


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.datakit_node = Node('Datakit_Root')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.plugin_name = 'base-ops'
        self.package_path = os.path.join(macro.DATAKIT_INSTALL_PATH, "visualtool-plugin")

    def test_base_ops(self):
        text = '----step1:卸载BaseOps插件 expect:成功----'
        self.log.info(text)
        self.log.info('----备份插件jar包----')
        cmd = f'''cd {self.package_path}; cp {self.plugin_name}* {macro.DATAKIT_INSTALL_PATH}'''
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '备份插件jar包失败')
        self.log.info('----卸载插件----')
        response = self.com_api.post_system_plugins_uninstall(self.plugin_name)
        self.log.info(response.json())
        self.assertEqual(200, response.json()['code'], '执行失败' + text)

    def tearDown(self):
        text = '----step2:恢复环境,安装BaseOps插件 expect:成功----'
        self.log.info(text)
        self.log.info('----恢复插件jar包----')
        cmd = f'''
        cd {macro.DATAKIT_INSTALL_PATH}; 
        mv {self.plugin_name}* {self.package_path};
        ls {self.package_path}|grep {self.plugin_name}'''
        res = self.datakit_node.sh(cmd).result()
        self.log.info(res)
        self.assertNotIn('No such file or directory', res, '执行失败')
        self.log.info('----安装插件----')
        jar_path = os.path.join(self.package_path, res)
        response = self.com_api.post_system_plugins_offline_install(jar_file=jar_path)
        self.log.info(response.json())
        self.assertEqual(self.plugin_name, response.json()['data']['pluginId'])
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
